package com.shigu;


import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Mr.赵
 * created on 2018/10/10
 */
public class HostUtil {

    public static String host="127.0.0.1";
    public static ThreadLocal<String> local=new ThreadLocal<>();

    /**
     * 无条件查host
     * @return
     */
    public static String selHost(){
        String host="127.0.0.1";
        try {
            RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
            HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
            host = request.getHeader("Host");
        } catch (IllegalStateException e) {
            if (StringUtils.isNotEmpty(local.get())) {
                return local.get();
            }
        }
        return host;
    }

    public static void setLocal(String host){
        local.set(host);
    }

}
